package com.whmnx.main.ui.model;

import android.app.Application;
import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.video.player.lib.base.IMediaPlayer;
import com.video.player.lib.constants.VideoConstants;
import com.video.player.lib.controller.DetailsCoverController;
import com.video.player.lib.manager.VideoPlayerManager;
import com.video.player.lib.view.VideoDetailsPlayerTrackView;
import com.video.player.lib.view.VideoTextureView;
import com.whmnx.base.bean.OrderBean;
import com.whmnx.base.bean.PingTanBean;
import com.whmnx.base.bean.ProductBean;
import com.whmnx.base.bean.ShopListBean;
import com.whmnx.base.constants.Constants;
import com.whmnx.base.constants.EventConstants;
import com.whmnx.base.http.CallBack;
import com.whmnx.base.http.HttpClient;
import com.whmnx.base.router.RouterActivityPath;
import com.whmnx.base.utils.ImageUtil;
import com.whmnx.base.view.GlideImageLoader;
import com.whmnx.base.view.RoundImageView;
import com.whmnx.base.view.ShowImagesDialog;
import com.whmnx.main.R;
import com.whmnx.main.databinding.FragmentCommodityDetailsBinding;
import com.whmnx.main.ui.activity.CommodityDetailsActivity;
import com.whmnx.main.ui.adapter.GirdDropDownAdpter;
import com.whmnx.main.ui.adapter.PineTanAdapter;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * author : huang
 * date   : 2020/9/27 0027 18:34
 * version: 1.0
 * @author Administrator
 */
public class ComDetailsModel extends ToolbarViewMainModel{

    private CommodityDetailsActivity mActivity;
    private FragmentCommodityDetailsBinding mBinding;

    public ObservableField<ProductBean> entity = new ObservableField<>();

    public ObservableField<String> Product_Sales = new ObservableField<>("");
    public ObservableField<String> Product_Name = new ObservableField<>("");
    public ObservableField<String> Product_SPEC = new ObservableField<>("");
    public ObservableField<String> Product_Price = new ObservableField<>("");
    public ObservableField<String> Product_Num = new ObservableField<>("");
    public ObservableField<String> Product_SPEC2 = new ObservableField<>("");
    private ProductBean productBean;
    public String PId;
    private PineTanAdapter mPingTanAdapter;


    private int count = 1;
    private int limitCount = 1;
    private String productSPEC_name;
    private String productSPEC_price;
    private boolean flag = false;
    private String productSPEC_groupPrice;
    private int type = 1;
    private Dialog dialogHead;

    public ComDetailsModel(@NonNull Application application) {
        super(application);
    }


    //给RecyclerView添加ObservableList
    public ObservableList observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding

    public void initToolbar(CommodityDetailsActivity commodityDetailsActivity, FragmentCommodityDetailsBinding binding, String Product_Id) {
        this.PId = Product_Id;
        this.mActivity = commodityDetailsActivity;
        this.mBinding = binding;
        VideoPlayerManager.getInstance().setVideoDisplayType(VideoConstants.VIDEO_DISPLAY_TYPE_CUT);
        DetailsCoverController coverController = new DetailsCoverController(mActivity);
        mBinding.videoPlayer.setVideoCoverController(coverController,false);
        setTitleText("商品详情");
        getProductdetail(Product_Id);
    }


    private void getProductdetail(String product_id) {
        Map<String, Object> params = new HashMap<>();
        params.put("ProductId",product_id);
        HttpClient.get(mActivity, Constants.GETPRODUCTDETAIL, params,new CallBack<ProductBean>() {
            @Override
            public void onSuccess(ProductBean result) {
                Constants.PRODUCTBEAN = result;
                Bundle bundle = new Bundle();
                bundle.putString("product_Remark", result.getProduct_Remark());
              //  mActivity.proShouMinFragment.setArguments(bundle);

                RxBus.getDefault().post(EventConstants.SHOU + "-" + result.Product_Remark);
                if (TextUtils.isEmpty(result.Product_Video)){
                    mBinding.tvVideo.setVisibility(View.GONE);
                    mBinding.tvPhoto.setVisibility(View.GONE);
                    mBinding.banner.setVisibility(View.VISIBLE);
                    mBinding.tvNum.setVisibility(View.VISIBLE);

                }else {
                    mBinding.tvVideo.setVisibility(View.VISIBLE);
                    mBinding.tvPhoto.setVisibility(View.VISIBLE);
                    mBinding.banner.setVisibility(View.GONE);
                    mBinding.videoPlayer.setVisibility(View.VISIBLE);
                    mBinding.tvNum.setVisibility(View.INVISIBLE);
                    ImageUtil.setImage(mBinding.videoPlayer.getCoverController().mVideoCover,Constants.HOST + result.Product_Video);
                    playVido(Constants.HOST + result.Product_Video,"");
                    mBinding.videoPlayer.startPlayVideo(Constants.HOST + result.Product_Video,"");
                }
                setBanner(result);
                productBean = result;
                entity.set(result);
                if (productBean.Product_Type == 1){  //拼团
                    mBinding.llPing.setVisibility(View.VISIBLE);
                    mBinding.rlPing.setVisibility(View.GONE);
                    mBinding.llPing2.setVisibility(View.VISIBLE);

                    //单独购买
                    mBinding.tvDianPrice.setText("￥" + result.SPECModel.get(0).ProductSPEC_Price);
                    //开团
                    mBinding.tvOpenPrice.setText("￥" + result.SPECModel.get(0).ProductSPEC_GroupPrice);
                    getGrouplist();
                }else {  //
                    mBinding.llPing.setVisibility(View.GONE);
                    mBinding.rlPing.setVisibility(View.VISIBLE);
                    mBinding.llPing2.setVisibility(View.GONE);
                    mBinding.tvOpenPrice.setVisibility(View.GONE);
                    mBinding.tvDianPrice.setVisibility(View.GONE);
                    mBinding.tvDian.setText("加入购物车");
                    mBinding.tvOpen.setText("立即购买");

                }
                Product_Name.set(result.Product_Name);
                Product_Price.set("￥" + result.Product_Price);
                Product_SPEC.set("规格：" + result.Product_SPEC);
                Product_Sales.set("销售：" + result.Product_Status);
                Product_SPEC2.set(result.Product_SPEC + "," + result.getShopNum() + "件");
            }
        });
    }

    /**
     * 拼团列表
     */
    private void getGrouplist() {
        mBinding.rvPing.setLayoutManager(new LinearLayoutManager(mActivity));
        mBinding.rvPing.setItemAnimator(new DefaultItemAnimator());
        mPingTanAdapter = new PineTanAdapter(mActivity);
        mBinding.rvPing.setAdapter(mPingTanAdapter);

        Map<String, Object> params = new HashMap<>();
        params.put("pId",PId);
        params.put("pageIndex",1);
        params.put("pageSize",20);
        HttpClient.post(mActivity, Constants.PRODUCTGROUPLIST, params,new CallBack<List<PingTanBean>>() {
            @Override
            public void onSuccess(List<PingTanBean> pingTanBeans) {  //ll_ping2
                if (pingTanBeans.size() == 0){
                    mBinding.llPing2.setVisibility(View.GONE);
                   // mBinding.rvPing.setVisibility(View.GONE);
                    mBinding.tv.setVisibility(View.GONE);
                }else {
                    mBinding.tv.setVisibility(View.VISIBLE);
                    mPingTanAdapter.replaceAll(pingTanBeans);
                    mBinding.tv.setText("已有" + pingTanBeans.size() + "人参团（满员发货）");
                }
            }
        });
    }

    private void addTextrueViewToView(VideoDetailsPlayerTrackView videoPlayer) {
        //先移除存在的TextrueView
        if(null!= IMediaPlayer.getInstance().getTextureView()){
            VideoTextureView textureView = IMediaPlayer.getInstance().getTextureView();
            if(null!=textureView.getParent()){
                ((ViewGroup) textureView.getParent()).removeView(textureView);
            }
            videoPlayer.mSurfaceView.addView(IMediaPlayer.getInstance().getTextureView(),
                    new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT, Gravity.CENTER));
        }
    }

    /**
     * 播放视频
     * @param url
     * @param headline
     */
    private void playVido(String url, String headline) {
        mBinding.videoPlayer.setDataSource(url, headline);
        mBinding.videoPlayer.setPlayerWorking(true);
        addTextrueViewToView(mBinding.videoPlayer);
        IMediaPlayer.getInstance().addOnPlayerEventListener(mBinding.videoPlayer);
        //手动检查播放器内部状态，同步常规播放器状态至全屏播放器
        IMediaPlayer.getInstance().checkedVidepPlayerState();
    }

    private void setBanner(ProductBean result) {
        //设置banner样式
        mBinding.banner.setBannerStyle(BannerConfig.NOT_INDICATOR);
        mBinding.banner.setIndicatorGravity(BannerConfig.CENTER);
        //设置图片加载器
        mBinding.banner.setImageLoader(new GlideImageLoader());
        //设置banner动画效果
        mBinding.banner.setBannerAnimation(Transformer.Default);
        //设置自动轮播，默认为true
        mBinding.banner.isAutoPlay(true);
        //设置轮播时间
        mBinding.banner.setDelayTime(1500);
        List<String> imgList = new ArrayList<>();
        if (result.Product_Image.contains(",")){
            String[] urls = result.Product_Image.split(",");
            for (int i = 0; i < urls.length; i++) {
                imgList.add(urls[i].contains(Constants.HOST) ? urls[i]: Constants.HOST + urls[i]);
            }
        }else {
            imgList.add(result.Product_Image.contains(Constants.HOST) ? result.Product_Image: Constants.HOST + result.Product_Image);
        }
        mBinding.banner.setImages(imgList);
        mBinding.banner.setIndicatorGravity(BannerConfig.CENTER)
                //以上内容都可写成链式布局，这是轮播图的监听。比较重要。方法在下面。
                .setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(int position) {
                        ShowImagesDialog showImagesDialog = new ShowImagesDialog(mActivity,imgList,position);
                        showImagesDialog.show();
                    }
                }).setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Product_Num.set(position+1 + "/" + imgList.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mBinding.banner.start();
    }


    public BindingCommand videoOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            mBinding.tvVideo.setTextColor(mActivity.getResources().getColor(R.color.white));
            mBinding.tvVideo.setBackgroundResource(R.drawable.red_drawable_oval2);
            mBinding.tvPhoto.setTextColor(mActivity.getResources().getColor(R.color.black));
            mBinding.tvPhoto.setBackgroundResource(R.drawable.wh_drawable_oval2);
            mBinding.tvNum.setVisibility(View.INVISIBLE);
            mBinding.videoPlayer.setVisibility(View.VISIBLE);
            mBinding.banner.setVisibility(View.GONE);
        }
    });

    //图片
    public BindingCommand photoClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            mBinding.tvPhoto.setTextColor(mActivity.getResources().getColor(R.color.white));
            mBinding.tvPhoto.setBackgroundResource(R.drawable.red_drawable_oval2);
            mBinding.tvVideo.setTextColor(mActivity.getResources().getColor(R.color.black));
            mBinding.tvVideo.setBackgroundResource(R.drawable.wh_drawable_oval2);
            mBinding.tvNum.setVisibility(View.VISIBLE);
            mBinding.videoPlayer.setVisibility(View.GONE);
            mBinding.banner.setVisibility(View.VISIBLE);
            VideoPlayerManager.getInstance().pause();

        }
    });

    //加入购物车
    public BindingCommand OnClickCommand2 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            showOpenDialog();
        }
    });
    //立即购买
    public BindingCommand OnClickCommand3 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            type = 2;
            showOpenDialog();
        }
    });

    /**
     * 弹出
     */
    private void showOpenDialog() {
        flag = false;
        dialogHead = new Dialog(mActivity, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_video3, null);

        RoundImageView ivImage = view.findViewById(R.id.iv_image);
        TextView tvName = view.findViewById(R.id.tv_Name);
        TextView tvPrice = view.findViewById(R.id.tv_price);
        TextView tvCountTitle = view.findViewById(R.id.tv_count_title);
        TextView tvJian = view.findViewById(R.id.tv_jian);
        TextView tvJia = view.findViewById(R.id.tv_jia);
        TextView tvCount = view.findViewById(R.id.tv_count);
        TextView tvAdd = view.findViewById(R.id.tv_add);
        LinearLayout rlShop = view.findViewById(R.id.rl_shop);
        LinearLayout rlOpen = view.findViewById(R.id.rl_open);
        TextView tvPeNum = view.findViewById(R.id.tv_peopleNum);
        TextView tv1 = view.findViewById(R.id.tv1);
        TextView tv2 = view.findViewById(R.id.tv2);
        TextView tv3 = view.findViewById(R.id.tv3);

        if (productBean.Product_Type == 0) {
           // rlShop.setVisibility(View.GONE);
            tv3.setText("立即购买");
            tvAdd.setText("加入购物车");
            tv2.setVisibility(View.GONE);
            tv1.setVisibility(View.GONE);
        } else {
            tvPeNum.setVisibility(View.VISIBLE);
            tvPeNum.setText(productBean.getPeopleNum() + "人拼团");
            //开团价格
            tv2.setText("￥" + productBean.SPECModel.get(0).ProductSPEC_GroupPrice);
            //单购购买
            tv1.setText("￥" + productBean.SPECModel.get(0).ProductSPEC_Price);
        }


        GridView gv = view.findViewById(com.whmnx.base.R.id.gv);

        if (productBean.Product_Image.contains(",")) {
            ImageUtil.setImage(ivImage, productBean.Product_Image.split(",")[0]);
        } else {
            ImageUtil.setImage(ivImage, productBean.Product_Image);
        }

        tvName.setText(productBean.Product_Name);
        tvPrice.setText("￥" + productBean.Product_Price);
        tvCountTitle.setText("数量: " + 1);

        view.findViewById(R.id.iv_close).setOnClickListener(v1 -> dialogHead.dismiss());
        //-
        tvJian.setOnClickListener(v12 -> {
            if (count > limitCount) {
                count -= limitCount;
                tvCountTitle.setText("数量: " + count);
                tvCount.setText(String.valueOf(count));
            }
        });
        //+
        tvJia.setOnClickListener(v12 -> {
            count += limitCount;
            tvCountTitle.setText("数量: " + count);
            tvCount.setText(String.valueOf(count));
        });

        //加入购物车
        rlShop.setOnClickListener(v13 -> {
            if (!flag) {
                ToastUtils.showShort("请先选择商品规格");
                return;
            }
            if (productBean.Product_Type == 0) {  //加入购物车
                addShop();
            }else {
                comOrder();
            }
        });

        //我要开团(立即购买)
        rlOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!flag) {
                    ToastUtils.showShort("请先选择商品规格");
                    return;
                }
                if (productBean.Product_Type == 0) {  //加入购物车
                    comOrder();
                } else {  //我要开团
                    Map<String, Object> params = new HashMap<>();
                    params.put("orderGroup_No", "");
                    params.put("orderGroup_ProductId", productBean.Product_Id);
                    params.put("orderGroup_ProductName", productBean.Product_Name);
                    params.put("orderGroup_ProductImage", productBean.Product_Image);
                    params.put("orderGroup_ProductSPEC", productSPEC_name);
                    params.put("orderGroup_ProductPrice", productSPEC_groupPrice);
                    params.put("orderGroup_ProductNum", count);
                    params.put("userInfo_Id", SPUtils.getInstance().getString(Constants.USERID));
                    HttpClient.post(mActivity, Constants.SPELLGROUP, params, new CallBack<OrderBean>() {
                        @Override
                        public void onSuccess(OrderBean result) {
                            Constants.ORDERBEAN = result;
                            ARouter.getInstance().build(RouterActivityPath.Home.COM).navigation();
                            dialogHead.dismiss();
                        }
                    });
                }
            }
        });


        dialogHead.setContentView(view);
        Window window = dialogHead.getWindow();
        if (window != null) {//宽高最大
            window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);//显示对话框//设置Dialog从窗体底部弹出
        }
            dialogHead.setCanceledOnTouchOutside(true);
            dialogHead.show();
            window.setGravity(Gravity.BOTTOM);//获取窗体的属性
            WindowManager.LayoutParams lp = window.getAttributes();//设置Dialog距离底部的距离
            //将属性设置给窗体
            window.setAttributes(lp);
            GirdDropDownAdpter cityAdapter = new GirdDropDownAdpter(mActivity, productBean.SPECModel);
            gv.setAdapter(cityAdapter);
            cityAdapter.setCheck(0);
            gv.setOnItemClickListener((parent, view1, position1, id) -> {
                flag = true;
                Button tv = view1.findViewById(R.id.tv);
                if (tv.isSelected() == false) {
                    productSPEC_name = productBean.SPECModel.get(position1).ProductSPEC_Name;
                    productSPEC_price = productBean.SPECModel.get(position1).ProductSPEC_Price;
                    productSPEC_groupPrice = productBean.SPECModel.get(position1).ProductSPEC_GroupPrice;
                    tv.setSelected(true);
                    if (productBean.Product_Type == 1) {
                        tv1.setText("￥" + productSPEC_price);
                        tv2.setText("￥" + productBean.SPECModel.get(position1).ProductSPEC_GroupPrice);
                        tvPrice.setText("￥" + productBean.SPECModel.get(position1).ProductSPEC_GroupPrice);
                    } else {
                        tvPrice.setText("￥" + productSPEC_price);
                    }
                } else {
                    tv.setSelected(false);
                }
            });
        }

    /**
     * 确认订单
     */
    private void comOrder() {
        //单独 购买
        List<ShopListBean> shopListBean = new ArrayList<>();
        List<ShopListBean.ProductListBean> productListBean = new ArrayList<>();
        productListBean.add(new ShopListBean.ProductListBean());
        productListBean.get(0).setProduct_Id(productBean.Product_Id);
        productListBean.get(0).setProduct_Name(productBean.Product_Name);
        productListBean.get(0).setProduct_Image(productBean.Product_Image);
        productListBean.get(0).setProduct_SPEC(productSPEC_name);
        productListBean.get(0).setProduct_Price(productSPEC_price + "");
        productListBean.get(0).setProduct_Num(count);
        shopListBean.add(new ShopListBean());

        shopListBean.get(0).setProductList(productListBean);
        shopListBean.get(0).setMId(productBean.UserInfo_Id);

        Map<String, Object> params = new HashMap<>();
        params.put("shopList", shopListBean);
        params.put("userInfo_Id", SPUtils.getInstance().getString(Constants.USERID));
        params.put("isGroup", 0);
        HttpClient.post(mActivity, Constants.GETORDERINFO, params, new CallBack<OrderBean>() {
            @Override
            public void onSuccess(OrderBean result) {
                Constants.ORDERBEAN = result;
                ARouter.getInstance().build(RouterActivityPath.Home.COM).navigation();
                dialogHead.dismiss();
            }
        });
    }

    /**
     * 加入购物车
     */
    private void addShop() {
        Map<String, Object> params = new HashMap<>();
        params.put("shopCart_ProductId", productBean.Product_Id);
        params.put("shopCart_ProductImage", productBean.Product_Image);
        params.put("shopCart_ProductName", productBean.Product_Name);
        params.put("shopCart_SPECName", productSPEC_name);
        params.put("shopCart_SPECMoney", productSPEC_price);
        params.put("shopCart_Num", count);
        params.put("userInfo_Id", SPUtils.getInstance().getString(Constants.USERID));

        HttpClient.post(mActivity, Constants.ADDSHOPCART, params, new CallBack<OrderBean>() {
            @Override
            public void onSuccess(OrderBean result) {
                ToastUtils.showShort("加入购物车成功");
                dialogHead.dismiss();
            }
        });
    }


    //选择规格
    public BindingCommand OnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            showOpenDialog();

           /* SelectPopUtil.showSpec(mActivity,productBean,null,0, new SelectParamPopupWindow.OnCancelListener() {
                @Override
                public void onCancel() {

                }

                @Override
                public void onBuy(String goodsId, String priceId, int count) {
                    Map<String, Object> params = new HashMap<>();
                    params.put("shopCart_ProductId",productBean.Product_Id);
                    params.put("shopCart_ProductImage",productBean.Product_Image);
                    params.put("shopCart_ProductName",productBean.Product_Name);
                    params.put("shopCart_SPECName",goodsId);
                    params.put("shopCart_SPECMoney",priceId);
                    params.put("shopCart_Num",count);
                    params.put("userInfo_Id",SPUtils.getInstance().getString(Constants.USERID));

                    HttpClient.post(mActivity, Constants.ADDSHOPCART, params,new CallBack<OrderBean>() {
                        @Override
                        public void onSuccess(OrderBean result) {
                             ToastUtils.showShort("加入购物车成功");
                           //  finish();
                        }
                    });
                }

                @Override
                public void onAddCar(String goodsId, String priceId, int count) {
                    List<ShopListBean>  shopListBean = new ArrayList<>();
                    List<ShopListBean.ProductListBean> productListBean = new ArrayList<>();
                    productListBean.add(new ShopListBean.ProductListBean());
                    productListBean.get(0).setProduct_Id(productBean.Product_Id);
                    productListBean.get(0).setProduct_Name(productBean.Product_Name);
                    productListBean.get(0).setProduct_Image(productBean.Product_Image);
                    productListBean.get(0).setProduct_SPEC(goodsId);
                    productListBean.get(0).setProduct_Price(priceId);
                    productListBean.get(0).setProduct_Num(count);
                    shopListBean.add(new ShopListBean());

                    shopListBean.get(0).setProductList(productListBean);
                    shopListBean.get(0).setMId(productBean.UserInfo_Id);

                    Map<String, Object> params = new HashMap<>();
                    params.put("shopList",shopListBean);
                    params.put("userInfo_Id", SPUtils.getInstance().getString(Constants.USERID));
                    params.put("isGroup", 0);
                    HttpClient.post(mActivity, Constants.GETORDERINFO, params,new CallBack<OrderBean>() {
                        @Override
                        public void onSuccess(OrderBean result) {
                            Bundle bundle =  new Bundle();
                            bundle.putSerializable("entity",result);
                            startActivity(ConfirmOrderActivity.class,bundle);
                        }
                    });
                }
            });*/
        }
    });


    @Override
    public void onDestroy() {
        super.onDestroy();
        VideoPlayerManager.getInstance().onDestroy();
    }
}
